package com.etrans.web.gps.business.report.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.report.domain.AbnomalVeVO;
import com.etrans.web.gps.business.report.domain.EnterpriseSwap;
import com.etrans.web.gps.business.report.domain.TrackInfoVO;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.DateUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.QueryOperators;

/**
 *报警统计Service
 * @author zhangw
 *
 */
@Service
public class AlarmStatisticsService extends BaseService{

	@Autowired
	public CommonService commonService;
	
	/**
	 * 根据区域id查询区域名称
	 * @return  
	 */
	public String queryAreaNameById(Integer area_id) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",area_id));
		return this.selectOne("alarmStatistics.queryThreeAreaNameById", param);
	}
	
	/**
	 * 
	 * @param queryContent
	 * @param timeType
	 * @param queryTime
	 * @param areaIdList
	 * @param page
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public PageVo getEnterpriseData(String alarmType, String timeType, String queryTime,
			List<Integer> areaIdList, int page, int pageSize) throws Exception{
		//时间查询条件-->"_id"过滤
		String table_name = "";
		String query_id = "";
		if ("day".equals(timeType) && queryTime.length() == 10) {
			query_id = queryTime.replace("-", "").substring(2, 8);
			table_name = "enterprise_swap";
		}else if ("week".equals(timeType) && queryTime.length() == 7) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			int year = Integer.parseInt((queryTime).split("-")[0]);
			int week = Integer.parseInt((queryTime).split("-")[1]);
			Map<String,Object> map =DateUtil.getYearAndWeekByDate(year, week);
			query_id = sdf.format(DateUtil.getStrToDate((String)map.get("Monday")));
			table_name = "enterprise_swap_week";
		}else if ("month".equals(timeType) && queryTime.length() == 7) {
			query_id = queryTime.replace("-", "").substring(2, 6)+"01";
			table_name = "enterprise_swap_month";
		}else {
			return null;
		}
		// 查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		//查询企业id
		/*if(queryContent != null && StringUtils.isNumeric(queryContent)){
			query_id = query_id + ":" + queryContent;
			whereMap.put("_id", query_id);
		}else {
			Pattern pattern = Pattern.compile("^"+query_id);
			whereMap.put("_id", pattern);
		}*/
		Pattern pattern = Pattern.compile("^"+query_id);
		whereMap.put("_id", pattern);
		whereMap.put("area_id", new BasicDBObject(QueryOperators.IN,areaIdList));
		whereMap.put(getAlarmField(alarmType), new BasicDBObject("$gte", 1));
		//按报警数量倒序
		HashMap<String,Object> sortMap = new HashMap<String,Object>();
		sortMap.put(getAlarmField(alarmType), Constant.MONGODB_DESC);
		List<EnterpriseSwap> resultList = MGTemplete.find("egov",table_name,whereMap,sortMap,page,pageSize,EnterpriseSwap.class,true);
		List<Map<String, Object>> list = new ArrayList<>();
		if (resultList != null && resultList.size() > 0) {
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", i+1);
				map.put("enterprise_name", resultList.get(i).getEnterprise_name());
				String alarm_type = "";
				int alarm_count = 0;
				if ("0".equals(alarmType)) {
					alarm_type = "全部报警";
					alarm_count =  resultList.get(i).getAlarm_count();
				}else if ("1".equals(alarmType)) {
					alarm_type = "超速报警";
					alarm_count =  resultList.get(i).getOverspeed_count();
				}else if ("2".equals(alarmType)) {
					alarm_type = "疲劳驾驶报警";
					alarm_count =  resultList.get(i).getTired_count();
				}else if ("3".equals(alarmType)) {
					alarm_type = "路线偏离报警";
					alarm_count =  resultList.get(i).getRoadoffset_count();
				}else if ("4".equals(alarmType)) {
					alarm_type = "2-5点禁行报警";
					alarm_count =  resultList.get(i).getProhibit_driving_count();
				}else if ("5".equals(alarmType)) {
					alarm_type = "夜间三级路面报警";
					alarm_count =  resultList.get(i).getNightly_3rd_count();
				}
				map.put("alarm_type", alarm_type);
				map.put("alarm_count", alarm_count);
				map.put("vehicle_count", resultList.get(i).getVehicle_count());
				map.put("alarm_vehicle_count", resultList.get(i).getAlarm_vehicle_count()+"");
				int alarm_vehicle_count = resultList.get(i).getAlarm_vehicle_count();
				map.put("per_vehicle_count", alarm_vehicle_count<1?0:Math.ceil(100.0*alarm_count/alarm_vehicle_count)/100);
				map.put("remark", "");
				list.add(map);
			}
		}
		PageVo pageVo = new PageVo();
		pageVo.setTotal(MGTemplete.findCount("egov", table_name, whereMap).intValue());
		pageVo.setRows(list);
		pageVo.setPage(page);
		return pageVo;
	}

	/**
	 * 
	 * @param queryContent
	 * @param timeType
	 * @param queryTime
	 * @param areaIdList
	 * @param page
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public PageVo getVehicleData(String alarmType, String timeType, String queryTime,
			List<Integer> areaIdList, int page, int pageSize) throws Exception{
		//时间查询条件-->"_id"过滤
		String table_name = "";
		String query_id = "";
		if ("day".equals(timeType) && queryTime.length() == 10) {
			query_id = queryTime.replace("-", "").substring(2, 8);
			table_name = "vehicle_swap";
		}else if ("week".equals(timeType) && queryTime.length() == 7) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			int year = Integer.parseInt((queryTime).split("-")[0]);
			int week = Integer.parseInt((queryTime).split("-")[1]);
			Map<String,Object> map =DateUtil.getYearAndWeekByDate(year, week);
			query_id = sdf.format(DateUtil.getStrToDate((String)map.get("Monday")));
			table_name = "vehicle_swap_week";
		}else if ("month".equals(timeType) && queryTime.length() == 7) {
			query_id = queryTime.replace("-", "").substring(2, 6)+"01";
			table_name = "vehicle_swap_month";
		}else {
			return null;
		}
		// 查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		//查询企业id
		/*if(queryContent != null && StringUtils.isNumeric(queryContent)){
			query_id = query_id + ":" + queryContent;
		}*/
		Pattern pattern = Pattern.compile("^"+query_id);
		whereMap.put("_id", pattern);
		whereMap.put(getAlarmField(alarmType), new BasicDBObject("$gte", 1));
		whereMap.put("area_id", new BasicDBObject(QueryOperators.IN,areaIdList));
		//按报警数量倒序
		HashMap<String,Object> sortMap = new HashMap<String,Object>();
		sortMap.put(getAlarmField(alarmType), Constant.MONGODB_DESC);
		List<AbnomalVeVO> resultList = MGTemplete.find("egov",table_name,whereMap,sortMap,page,pageSize,AbnomalVeVO.class,true);
		List<Map<String, Object>> list = new ArrayList<>();
		if (resultList != null && resultList.size() > 0) {
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", i+1);
				map.put("enterprise_name", resultList.get(i).getEnterprise_name());
				String alarm_type = "";
				int alarm_count = 0;
				if ("0".equals(alarmType)) {
					alarm_type = "全部报警";
					alarm_count =  resultList.get(i).getAlarm_count();
				}else if ("1".equals(alarmType)) {
					alarm_type = "超速报警";
					alarm_count =  resultList.get(i).getOverspeed_count();
				}else if ("2".equals(alarmType)) {
					alarm_type = "疲劳驾驶报警";
					alarm_count =  resultList.get(i).getTired_count();
				}else if ("3".equals(alarmType)) {
					alarm_type = "路线偏离报警";
					alarm_count =  resultList.get(i).getRoadoffset_count();
				}else if ("4".equals(alarmType)) {
					alarm_type = "2-5点禁行报警";
					alarm_count =  resultList.get(i).getProhibit_driving_count();
				}else if ("5".equals(alarmType)) {
					alarm_type = "夜间三级路面报警";
					alarm_count =  resultList.get(i).getNightly_3rd_count();
				}
				map.put("alarm_type", alarm_type);
				map.put("alarm_count", alarm_count);
				map.put("vehicle_no", resultList.get(i).getVehicle_no());
				map.put("remark", "");
				list.add(map);
			}
		}
		PageVo pageVo = new PageVo();
		pageVo.setTotal(MGTemplete.findCount("egov", table_name, whereMap).intValue());
		pageVo.setRows(list);
		pageVo.setPage(page);
		return pageVo;
	}

	public static String getAlarmField(String alarmType) {
		switch (alarmType) {
			case "0":
				return "alarm_count";
			case "1":
				return "overspeed_count";
			case "2":
				return "tired_count";
			case "3":
				return "roadoffset_count";
			case "4":
				return "prohibit_driving_count";
			case "5":
				return "nightly_3rd_count";
			default :
				return "alarm_count";
		}
	}

	public List<Map<String, String>> exportEnterpriseDataList(String alarmType, String table_name, String query_id,
			int queryArea) {
		// 查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		//查询企业id
		/*if(queryContent != null && StringUtils.isNumeric(queryContent)){
			query_id = query_id + ":" + queryContent;
			whereMap.put("_id", query_id);
		}else {
			Pattern pattern = Pattern.compile("^"+query_id);
			whereMap.put("_id", pattern);
		}*/
		Pattern pattern = Pattern.compile("^"+query_id);
		whereMap.put("_id", pattern);
		whereMap.put("area_id", queryArea);
		whereMap.put(getAlarmField(alarmType), new BasicDBObject("$gte", 1));
		//按报警数量倒序
		HashMap<String,Object> sortMap = new HashMap<String,Object>();
		sortMap.put(getAlarmField(alarmType), Constant.MONGODB_DESC);
		List<EnterpriseSwap> resultList = MGTemplete.find("egov",table_name,whereMap,sortMap,EnterpriseSwap.class,true);
		List<Map<String, String>> list = new ArrayList<>();
		if (resultList != null && resultList.size() > 0) {
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, String> map = new HashMap<>();
				map.put("ranking", i+1+"");
				map.put("enterpriseName", resultList.get(i).getEnterprise_name());
				int alarm_count = 0;
				if ("0".equals(alarmType)) {
					alarm_count =  resultList.get(i).getAlarm_count();
				}else if ("1".equals(alarmType)) {
					alarm_count =  resultList.get(i).getOverspeed_count();
				}else if ("2".equals(alarmType)) {
					alarm_count =  resultList.get(i).getTired_count();
				}else if ("3".equals(alarmType)) {
					alarm_count =  resultList.get(i).getRoadoffset_count();
				}else if ("4".equals(alarmType)) {
					alarm_count =  resultList.get(i).getProhibit_driving_count();
				}else if ("5".equals(alarmType)) {
					alarm_count =  resultList.get(i).getNightly_3rd_count();
				}
				map.put("alarmCount", alarm_count+"");
				map.put("vehicleCount", resultList.get(i).getVehicle_count()+"");
				map.put("alarmVehicleCount", resultList.get(i).getAlarm_vehicle_count()+"");
				int alarmVehicleCount = resultList.get(i).getAlarm_vehicle_count();
				map.put("alarmAvg", alarmVehicleCount<1?"0":Math.ceil(100.0*alarm_count/alarmVehicleCount)/100+"");
				map.put("remark", "");
				list.add(map);
			}
		}
		return list;
	}
	
	public List<Map<String, String>> exportVehicleDataList(String alarmType, String table_name, String query_id, 
			int queryArea) throws Exception{
		// 查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		//查询企业id
		/*if(queryContent != null && StringUtils.isNumeric(queryContent)){
			query_id = query_id + ":" + queryContent;
		}*/
		Pattern pattern = Pattern.compile("^"+query_id);
		whereMap.put("_id", pattern);
		whereMap.put(getAlarmField(alarmType), new BasicDBObject("$gte", 1));
		whereMap.put("area_id", queryArea);
		//按报警数量倒序
		HashMap<String,Object> sortMap = new HashMap<String,Object>();
		sortMap.put(getAlarmField(alarmType), Constant.MONGODB_DESC);
		List<AbnomalVeVO> resultList = MGTemplete.find("egov",table_name,whereMap,sortMap,AbnomalVeVO.class,true);
		List<Map<String, String>> list = new ArrayList<>();
		if (resultList != null && resultList.size() > 0) {
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, String> map = new HashMap<>();
				map.put("ranking", i+1+"");
				map.put("enterpriseName", resultList.get(i).getEnterprise_name());
				int alarm_count = 0;
				if ("0".equals(alarmType)) {
					alarm_count =  resultList.get(i).getAlarm_count();
				}else if ("1".equals(alarmType)) {
					alarm_count =  resultList.get(i).getOverspeed_count();
				}else if ("2".equals(alarmType)) {
					alarm_count =  resultList.get(i).getTired_count();
				}else if ("3".equals(alarmType)) {
					alarm_count =  resultList.get(i).getRoadoffset_count();
				}else if ("4".equals(alarmType)) {
					alarm_count =  resultList.get(i).getProhibit_driving_count();
				}else if ("5".equals(alarmType)) {
					alarm_count =  resultList.get(i).getNightly_3rd_count();
				}
				map.put("alarmCount", alarm_count+"");
				map.put("vehicleNo", resultList.get(i).getVehicle_no());
				map.put("remark", "");
				list.add(map);
			}
		}
		return list;
	}
	/**
	 * 
	 * @param startDate
	 * @param endDate
	 * @param areaId
	 * @return
	 */
	public List<Map<String, String>> getVehicleOverSpeedList(Date startDate, Date endDate, int areaId){
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",areaId));
		List<HashMap<String, Object>> vehcileList = this.selectList("alarmStatistics.queryVehcileListById", param);
		if (vehcileList == null || vehcileList.size() == 0) {
			return null;
		}
		HashMap<Integer, String> vehcileMap = new HashMap<Integer, String>();
		for (HashMap<String, Object> hMap : vehcileList) {
			vehcileMap.put(Integer.valueOf(hMap.get("id") + ""),hMap.get("enterprise_name")+"");
		}
		// 查询条件
		HashMap<String,Object> whereMap = new HashMap<String, Object>();
		whereMap.put("gps_speed", new BasicDBObject("$gte", 100));
		//指定查询字段
		HashMap<String,Object> project = new HashMap<String, Object>();
		project.put("vehicle_id", 1);
		project.put("vehicle_no", 1);
		project.put("gps_time", 1);
		project.put("gps_speed", 1);
		//查询表
		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		Map<Integer, TrackInfoVO> resultMap = new HashMap<Integer, TrackInfoVO>();
		while (startDate.before(endDate)) {
			String tableName = "gps_info_"+new SimpleDateFormat("yyMMdd").format(startDate);
			List<TrackInfoVO> list = MGTemplete.find("egov",tableName,whereMap,TrackInfoVO.class,false,project);
			cal.add(Calendar.DAY_OF_YEAR,1);
			startDate = cal.getTime();
			if (list == null || list.size() == 0) {
				continue;
			}
			for (TrackInfoVO vo : list) {
				Integer key = vo.getVehicle_id();
				if (vehcileMap.containsKey(key)) {
					if (resultMap.containsKey(key)) {
						if (resultMap.get(key).getGps_speed()<vo.getGps_speed()) {
							resultMap.get(key).setGps_speed(vo.getGps_speed());
						}
					}else {
						vo.setEnterprise_name(vehcileMap.get(key)+"");
						resultMap.put(key, vo);
					}
				}
			}
		}
		List<TrackInfoVO> resultList = new ArrayList<TrackInfoVO>(resultMap.values());
		Collections.sort(resultList,Collections.reverseOrder(new Comparetores()));
		List<Map<String, String>> list = new ArrayList<>();
		if (resultList != null && resultList.size() > 0) {
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, String> map = new HashMap<>();
				map.put("ranking", i+1+"");
				map.put("enterpriseName", resultList.get(i).getEnterprise_name());
				map.put("vehicleNo", resultList.get(i).getVehicle_no());
				map.put("alarmSpeed", resultList.get(i).getGps_speed()+"");
				map.put("remark", "");
				list.add(map);
			}
		}
		return list;
	}
	
	/**
	 * 排序
	 * @ClassName:  Comparetores  
	 * @param: Comparator<T>
	 */
	public static class Comparetores implements Comparator<TrackInfoVO>{
		public int compare(TrackInfoVO vo1, TrackInfoVO vo2) {
	        return vo1.getGps_speed()-vo2.getGps_speed()>0?1:-1;
		}
	}
}
